//
//  MyCardsViewController.m
//  Guazi
//
//  Created by koolearn on 11-6-2.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "Card.h"
#import "CardCell.h"
#import "MyCardsViewController.h"
#import "CardDetailViewController.h"
#import "CardEditViewController.h"
#import "GuaziAppDelegate.h"
#import "NetworkUtil.h"

@interface MyCardsViewController(private)
- (void) loadData;
- (void) didLoadData:(TwitterClient*)sender object:(NSObject*)object;
- (void) buildBarItem;
@end


@implementation MyCardsViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}


- (void)dealloc
{
    [cards release];
    [super dealloc];
}


- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}


#pragma mark - load data from server

- (BOOL) isExistCard:(long long)cardId
{
    for ( Card* card in cards ) {
        if ( card.cardId == cardId ) return YES;
    }
    return NO;
}


- (void) loadData
{
    if ( client ) return;
    
    client = [[TwitterClient alloc] initWithTarget:self action:@selector(didLoadData:object:)];
    [client getMyCards];
}


- (void) didLoadData:(TwitterClient*)sender object:(NSObject*)object
{
    client = nil;
    if ( !object || ![object isKindOfClass:[NSArray class]] ) return;
    
    NSArray* arr = (NSArray*) object;
    if ( [arr count] == 0 ) return;
    
    for ( id o in arr ) {
        if ( ![o isKindOfClass:[NSDictionary class]] ) continue;
        NSDictionary* dic = (NSDictionary*) o;
        Card* card = [Card cardWithJsonDictionary:dic];
        [card updateDB];
        
        if ( ![self isExistCard:card.cardId] ) {
            [cards addObject:card];
        }
    }
    
    [self.tableView reloadData];
}


#pragma mark - user operations

- (void) addCard
{
    CardEditViewController* controller = [[CardEditViewController alloc] initWithStyle:UITableViewStyleGrouped];
    [self.navigationController pushViewController:controller animated:YES];
    [controller release];
}


#pragma mark - refresh operations

- (void) refreshAddCard:(Card*)card
{
	[cards addObject:card];
	[self.tableView reloadData];
}


- (void) refreshModifyCard:(Card*)card
{
	int index = -1;
	for ( int i=0; i<[cards count]; i++ ) {
		Card* c = [cards objectAtIndex:i];
		if ( c.cardId == card.cardId ) {
			index = i;
			break;
		}
	}
	
	if ( index >= 0 ) {
		Card* c = [cards objectAtIndex:index];
		[c setValuesFromCard:card];
		NSArray* array = [NSArray arrayWithObject:[NSIndexPath indexPathForRow:index inSection:0]];
		[self.tableView reloadRowsAtIndexPaths:array withRowAnimation:UITableViewRowAnimationNone];
	}
	
	/*for (Card* c in cards) {
		if ( c.cardId == card.cardId ) {
			[c setValuesFromCard:card];
			break;
		}
	}
	[self.tableView reloadData];*/
}


- (void) refreshDeleteCard:(Card*)card
{
	Card* theCard = nil;
	for ( Card* c in cards ) {
		if ( c.cardId == card.cardId ) {
			theCard = c;
			break;
		}
	}
	
	if ( theCard ) {
		[cards removeObject:theCard];
		[self.tableView reloadData];
	}
}


#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationItem.title = @"我的名片";

    [self buildBarItem];
    
    long long userId = [GuaziAppDelegate getAppDelegate].user.userId;
    cards = [(NSMutableArray*) [Card cardsForUser:userId] retain];
    
    if ( [NetworkUtil isbroadbandAvailable] ) {
        [self loadData];
    }
}


- (void) buildBarItem
{
    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addCard)] autorelease];
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    [cards release];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [cards count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"MyCardsCell";
    
    CardCell *cell = (CardCell*) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[CardCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
    Card* card = [cards objectAtIndex:indexPath.row];
    cell.card = card;
    cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
    
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}


- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
{
    Card* card = [cards objectAtIndex:indexPath.row];
    card.user = [GuaziAppDelegate getAppDelegate].user;
    CardDetailViewController* controller = [[CardDetailViewController alloc] initWithCard:card];
    [self.navigationController pushViewController:controller animated:YES];
    [controller release];
}


@end
